package com.learn.support;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;

import java.util.Set;

/**
 * Description
 * Copyright © 启明星辰 版权所有
 *
 * @author chenjiquan
 * @date 2024-08-05
 */
public class ZhouyuBeanDefinitionScanner extends ClassPathBeanDefinitionScanner {

	public ZhouyuBeanDefinitionScanner(BeanDefinitionRegistry registry) {
		super(registry);
	}

	@Override
	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {

		// 利用spring的ClassPathBeanDefinitionScanner帮我扫描注册
		Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);

		for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
			GenericBeanDefinition beanDefinition = (GenericBeanDefinition) beanDefinitionHolder.getBeanDefinition();

			// setSqlSession
			beanDefinition.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);

			// 设置构造函数的入参（MapperFactoryBean.mapperInterface属性）
			beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName());
			beanDefinition.setBeanClassName(ZhouyuFactoryBean.class.getName());
		}
		return beanDefinitionHolders;
	}

	/**
	 * 重写需要注册的bean可以是接口类
	 * @param beanDefinition the bean definition to check
	 * @return
	 */
	@Override
	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
		return beanDefinition.getMetadata().isInterface();
	}
}
